<?php
require_once("../cofd/common.php");
$json_j = file_get_contents("php://input");
$json_jx = json_decode($json_j, true);
$title = $json_jx["title"];
$content = $json_jx["content"];
$userid = $json_jx["userid"];
function generateUniqueId($conn, $length = 8) {
    $characters = '0123456789';
    $id = '';
    do {
        $id = '';
        for ($i = 0; $i < $length; $i++) {
            $id .= $characters[rand(0, strlen($characters) - 1)];
        }
        $result = $conn->query("SELECT 1 FROM post WHERE id = '$id'");
        if ($result !== false && $result->num_rows > 0) {
            $id = ''; 
        } else {
            break;
        }
    } while ($id === '');
    return $id;
}

$id = generateUniqueId($conn);
if ($id === false) {
    echo json_encode(array("code" => 400, "msg" => "id解析失败"));
    return;
}
$sql = "INSERT INTO post (id,phead, pbody,zt,fromer) VALUES ('$id','$title', '$content','0', '$userid')";
if ($conn->query($sql) === TRUE) {
    echo json_encode(array("code" => 200, "msg" => "发帖成功，请耐心等待审核"));
}else{
    echo json_encode(array("code" => 400, "msg" => "发帖失败"));
}